package com.bootdo.common.service;

import com.bootdo.common.persistence.CrudDao;
import com.bootdo.common.persistence.DataEntity;
import com.bootdo.common.persistence.Page;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.transaction.annotation.Transactional;

import java.util.List;

/**
 * Created by Administrator on 2018/7/3.
 */
@Transactional(readOnly = true)
public abstract class CrudService<D extends CrudDao<T>, T extends DataEntity<T>> extends BaseService {

    /**
     * 持久层对象
     */
    @Autowired
    protected D dao;

    /**
     * 获取单条数据
     * @param id
     * @return
     */
    public T get(String id) {
        return dao.get(id);
    }

    /**
     * 获取单条数据
     * @param entity
     * @return
     */
    public T get(T entity) {
        return dao.get(entity);
    }

    /**
     * 查询列表数据
     * @param entity
     * @return
     */
    public List<T> findList(T entity) {
        return dao.findList(entity);
    }

    /**
     * 查询分页数据
     * @param page 分页对象
     * @param entity
     * @return
     */
    public Page<T> findPage(Page<T> page, T entity) {
        entity.setPage(page);
        page.setRows(dao.findList(entity));
        return page;
    }

    /**
     * 保存数据（插入或更新）
     * @param entity
     */
    @Transactional(readOnly = false)
        public void save(T entity) {
            boolean falg=entity.getIsNewRecord();
            if (entity.getIsNewRecord()){
                entity.preInsert();
                dao.insert(entity);
            }else{
                entity.preUpdate();
                dao.update(entity);
            }
    }

    /**
     * 保存数据（插入或更新）带返回值
     * @param entity
     */
    @Transactional(readOnly = false)
    public T saveEntity(T entity) {
        boolean falg=entity.getIsNewRecord();
        if (entity.getIsNewRecord()){
            entity.preInsert();
            dao.insert(entity);
        }else{
            entity.preUpdate();
            dao.update(entity);
        }
        return entity;
    }

    /**
     * 删除数据
     * @param entity
     */
    @Transactional(readOnly = false)
    public void delete(T entity) {
        dao.delete(entity);
    }

    /**
     * 状态数据
     * @param entity
     */
    @Transactional(readOnly = false)
    public void verify(T entity) {
        dao.verify(entity);
    }


}
